package com.ycsj.goldmedalnewconcept.main.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ycsj.common.appupdate.AppBean;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.toast.ToastUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.PermissionUtil;
import com.ycsj.goldmedalnewconcept.master.activity.MasterMainActivity;
import com.ycsj.goldmedalnewconcept.parent.activity.ParentMainActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentGetpetOneActivity;
import com.ycsj.goldmedalnewconcept.student.activity.StudentMainActivity;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherMainActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 启动页面
 * Created by Administrator on 2018/1/11 0011.
 */

public class WelcomeActivity extends AppCompatActivity {

    private String role;

    private String pettype;

    private Handler handler;

    //默认组件
    private ComponentName componentNameDefault;

    //春节组件
    private ComponentName yearComponent;

    //春节的Icon标识
    String yearPath = "com.ssyc.jpxb.year";

    //默认的Icon标识
    String defPath = "com.ssyc.jpxb.def";

    //机构名称
    private TextView tv_school_name;

    //机构名称
    private ImageView iv_logo;

    //包含机构和名称的布局
    private LinearLayout ll_logo;

    //版本更新的接口
    public static final String APKVERSONURL = "https://s.moregolden.com/ycsj_platform_nce2/AppVerMsg";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_welcome);

        judgeVersion();

    }

    //判断用户版本4.2以下直接退出APP
    private void judgeVersion() {
        int sdkVersion = android.os.Build.VERSION.SDK_INT;
        if (sdkVersion <= 21) {
            //小于4.2以下
            ToastUtils.show("当前版本过低,不能使用APP");
            finish();

        } else {

            //初始化账号
            initData();

            //初始化视图
            initView();

            //请求Icon接口
//        http();

            //跳转界面
//        IntentActivity();

        }

    }

    private void initView() {
        tv_school_name = findViewById(R.id.tv_school_name);
        iv_logo = findViewById(R.id.iv_logo);
        ll_logo = findViewById(R.id.ll_logo);


        if (!TextUtils.isEmpty(AccountUtils.getSchoolName(this))) {
            tv_school_name.setText(AccountUtils.getSchoolName(this));
        } else {
            tv_school_name.setText("金牌新概念");
        }

        ImageUtil.displayImage(this, iv_logo, AccountUtils.getLogo(this)
                , R.drawable.ic_icon);

        //执行Logo动画
        ObjectAnimator anim = ObjectAnimator.ofFloat(ll_logo, "alpha", 0, 1);
        anim.setDuration(1700);
        anim.setInterpolator(new LinearInterpolator());
        anim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //跳转界面
                IntentActivity();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        anim.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDenin = false;
        if (requestCode == PermissionUtil.REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDenin = true;
                    break;
                }

            }
            if (hasPermissionDenin) {
                Toast.makeText(this, "未同意权限将无法使用相关功能", Toast.LENGTH_LONG).show();
            }
//            IntentActivity();
        }
    }


    /**
     * 请求服务器获取Icon接口
     */
    private void http() {

        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        params.put("app", "android");
        params.put("page", "0");
        params.put("platform", "8");


        OkHttpUtils.post().url(APKVERSONURL).params(params).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                IntentActivity();
            }

            @Override
            public void onResponse(String response, int id) {

                //服务器返回的版本数据json
                AppBean appBean = null;

                try {
                    appBean = GsonUtil.jsonToBean(response, AppBean.class);
                    //获取动态图标
                    if (!TextUtils.isEmpty(appBean.getServerjson().getApp_icon())) {

                        //实现APP的动态替换图标,初始化组件
                        initCompent();

                        //切换组件更改Icon
                        changeIconMethod(appBean.getServerjson().getApp_icon());
                    }

                } catch (Exception e) {
                    Log.i("test", "解析版更新数据错误");
                    IntentActivity();
                }
            }
        });
    }


    /**
     * 初始化组件的方法
     */
    private void initCompent() {
        yearComponent = new ComponentName(getApplication(), yearPath);
        componentNameDefault = new ComponentName(getApplication(), defPath);
    }


    /**
     * 启用组件
     *
     * @param componentName 重要方法
     */
    private void enableComponent(Activity activity, ComponentName componentName) {
        PackageManager pm = activity.getPackageManager();
        int state = pm.getComponentEnabledSetting(componentName);
        if (PackageManager.COMPONENT_ENABLED_STATE_ENABLED == state) {
            //已经启用
            return;
        }
        pm.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }


    /**
     * 禁用组件
     *
     * @param componentName 重要方法
     */
    private void disableComponent(Activity activity, ComponentName componentName) {
        PackageManager pm = activity.getPackageManager();
        int state = pm.getComponentEnabledSetting(componentName);
        if (PackageManager.COMPONENT_ENABLED_STATE_DISABLED == state) {
            //已经禁用
            return;

        }
        pm.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    /**
     * 根绝服务器返回的标识动态切换Icon的方法
     */
    private void changeIconMethod(String yearIcon) {

        //Icon是否变化
        if (!yearIcon.equals(SPUtil.getString(this, SpKeys.LASTICON))) {

            if (TextUtils.isEmpty(yearIcon) || "0".equals(yearIcon)) {
                //默认Icon
                disableComponent(this, yearComponent);
                enableComponent(this, componentNameDefault);
            } else if ("1".equals(yearIcon)) {
                //春节Icon
                disableComponent(this, componentNameDefault);
                enableComponent(this, yearComponent);
            }
            SPUtil.put(this, SpKeys.LASTICON, yearIcon);
            IntentActivity();
        } else {
            IntentActivity();
        }
    }


    /**
     * 初始化账号系统
     */
    private void initData() {
        role = AccountUtils.getRole(this);
        pettype = SPUtil.getString(this, SpKeys.SERVICEPETTYPE);
        handler = new Handler();
    }

    /**
     * 跳转界面的方法
     */
    private void IntentActivity() {
        //延迟跳转


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                goActivity();
            }
        }, 1500);
    }


    /**
     * 动画结束后判断是否第一次进入
     * true:跳转到Glide界面
     * false:根据角色跳转到不同角色的对应的逻辑界面
     */
    private void goActivity() {

        if (!SPUtil.getBoolean(this, SpKeys.ISFIRST)) {
            //是第一次登陆
            UiUtils.startActivity(this, GuideActivity.class);
            SPUtil.put(this, SpKeys.ISFIRST, true);
        } else {
            //是否登录
            if ("1".equals(AccountUtils.getIslogin(this))) {
                //学生身份
                if ("0".equals(role)) {
                    //是否领取宠物
                    if (!TextUtils.isEmpty(pettype)) {
                        //学生登录并且已经领取过宠物,跳到主界面
                        UiUtils.startActivity(WelcomeActivity.this, StudentMainActivity.class);
                    } else {
                        //学生登录但是没有领取宠物,跳转到领取宠物界面
                        UiUtils.startActivity(WelcomeActivity.this, StudentGetpetOneActivity.class);
                    }
                } else if ("1".equals(role)) {
                    //家长
                    UiUtils.startActivity(WelcomeActivity.this, ParentMainActivity.class);
                } else if ("2".equals(role)) {
                    // 老师
                    UiUtils.startActivity(WelcomeActivity.this, TeacherMainActivity.class);
                } else if ("3".equals(role)) {
                    //校长
                    UiUtils.startActivity(WelcomeActivity.this, MasterMainActivity.class);
                }
            } else {
                //未登录,角色选择界面
                UiUtils.startActivity(WelcomeActivity.this, ChooseRoleActivity.class);
            }
        }

        finish();
    }

    @Override
    protected void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }


}
